﻿
Imports System.Threading

Public Structure singleentry
    Private Const free As Int32 = 0
    Private Const inuse As Int32 = 1
    Private state As Int32

    Shared Sub New()
        assert(free = [default](Of Int32)())
    End Sub

    Public Function in_use() As Boolean
        Return atomic.read(state) = inuse
    End Function

    Public Function mark_in_use() As Boolean
        Return Interlocked.CompareExchange(state, inuse, free) = free
    End Function

    Public Sub release()
#If DEBUG Then
        assert(in_use())
#End If
        mark_not_in_use()
    End Sub

    Public Sub mark_not_in_use()
        atomic.eva(state, free)
    End Sub
End Structure